
#ifndef __MOTOR_CONTROL_H
#define __MOTOR_CONTROL_H

#include "FreeRTOS.h"
#include "task.h"
#include "main.h"
#include "cmsis_os.h"
#include "usart.h"
#include <stdio.h>
#include <string.h>
#include "tim.h"
#include <stdint.h>
#include <stdlib.h>
#include <rbus_parser.h>

// 电机引脚定义
#define LF_FORWARD_TIM   &htim1
#define LF_FORWARD_CH    TIM_CHANNEL_2
#define LF_BACKWARD_TIM  &htim1  
#define LF_BACKWARD_CH   TIM_CHANNEL_1

#define RF_FORWARD_TIM   &htim1
#define RF_FORWARD_CH    TIM_CHANNEL_4
#define RF_BACKWARD_TIM  &htim1
#define RF_BACKWARD_CH   TIM_CHANNEL_3

#define LB_FORWARD_TIM   &htim9
#define LB_FORWARD_CH    TIM_CHANNEL_1
#define LB_BACKWARD_TIM  &htim9
#define LB_BACKWARD_CH   TIM_CHANNEL_2

#define RB_FORWARD_TIM   &htim12
#define RB_FORWARD_CH    TIM_CHANNEL_1
#define RB_BACKWARD_TIM  &htim12
#define RB_BACKWARD_CH   TIM_CHANNEL_2


// 或者设置死区，避免电机无法启动
#define MIN_PWM 60   // 电机启动所需的最小PWM
#define MAX_PWM 90

// 摇杆结构体
typedef struct {
    int16_t x;  // 水平方向 (-100 to 100)
    int16_t y;  // 垂直方向 (-100 to 100)
} JoystickDir;

// 电机控制结构体
typedef struct {
    TIM_HandleTypeDef* forward_tim;
    uint32_t forward_ch;
    TIM_HandleTypeDef* backward_tim;  
    uint32_t backward_ch;
} Motor;

// 函数声明
void Motor_Init(void);
void Motor_Run(RBUS_parser *rbus_parser);
void set_motor_speed(Motor motor, int16_t speed);
void mecanum_drive(JoystickDir left_joy, JoystickDir right_joy);
void stop_all_motors(void);
void brake_all_motors(void);
int16_t map(int16_t x, int16_t in_min, int16_t in_max, int16_t out_min, int16_t out_max);
void simple_drive(int16_t joy_x, int16_t joy_y);

// 全局电机对象声明
extern Motor left_front, right_front, left_back, right_back;

#endif